<?php
// =====================================================================================
// ==============投注=====================================================================
// =====================================================================================
/**
 * 投注K3
 * @param array $data: 投注信息
 * @return $res;
 */
function betting_k3($data){
    global $db;
    // 检查玩法
    $play      = strtoupper($data['play']);
    $play      = substr(stristr($play, '_'), '1');
    $p_conf    = k3Item();
    $p_conf    = $p_conf[$play];
    $weimiao   = microtime(true);
    $bet_arr   = array();
    $orderno   = 'TZ' . date('YmdHis') . str_pad(substr($weimiao, strpos($weimiao, '.') + 1), '4', 0);
    $order_pay = 0;
    // odds赔率，在和值玩法中取每注对应的数值
    $oddsTitleKey = array();
    foreach ($p_conf['item'] as $ik => $iv){
        $oddsTitleKey[$iv['title']] = $iv;
    }
    // 返点赔率信息
    $codeKeyList    = getUserRpsData($db, $data['lott_id']);
    
    // 订单主表:原设计不分订单主从表， 这里重新加入统一订单主从。
    $orderMain    = array();
    // 订单副表
    $orderItem    = array();
    // 拆分出投注的每个内容
    $bettingData  = explode(',', $data['bet']);
    $item['lott_id'] = $data['lott_id'];
    // 防止用户选号后等下一期的时候提交，期号会保持上一期的数据，这里获取最新的期号信息来填充数据
    $nowTime          = time();
    $nowPeriodInfoSql = 'SELECT id FROM ' . Table('lottery_k3') . ' WHERE tid = ' . $data['lott_id'] . ' AND starttime <= ' . $nowTime . ' ORDER BY id DESC LIMIT 1';
    $nowPeriodInfo    = $db->getrow($nowPeriodInfoSql);
    $item['period_id']   = $nowPeriodInfo['id'];
    switch ($play){
        case 'HE':
        case 'STHTX':
        case 'STHDX':
        case 'SLHTX':
        case 'ETHFX':
            // 三同号单选，每一个投注项都是单独一注
            foreach ($bettingData as $k => $v){
//                 $orderItem[$k]['order_no']   = $orderno;
                $orderItem[$k]['betting_str']= $data['bet'];
                $orderItem[$k]['period_id']  = $nowPeriodInfo['id'];
                $orderItem[$k]['lott_id']    = $data['lott_id'];
                
                $orderItem[$k]['en_play']    = $play;
                $orderItem[$k]['cn_play']    = $p_conf['title'];
                $orderItem[$k]['betting_no'] = $v;
                $orderItem[$k]['num']        = 1;    // 手机端每次投注都是1注
                $orderItem[$k]['multiple']   = 1;    // K3默认倍数
                $orderItem[$k]['money_unit'] = 1;    // K3默认金额单位
                $orderItem[$k]['eo_money']   = $data['eo_money'];
                // 总金额 = 投注数num*倍数multiple*金额单位money_unit*单注基础金额数eo_money
                $orderItem[$k]['money']      = $orderItem[$k]['num'] * $orderItem[$k]['multiple'] * $orderItem[$k]['money_unit'] * $orderItem[$k]['eo_money'];
//                 $orderItem[$k]['odds']       = $oddsTitleKey[$v]['odds'];
                $orderItem[$k]['prize']      = '0';
                $orderItem[$k]['winner']     = '0';
                $order_pay += 1 * $data['eo_money'];
                $re_play  = $play;
                if ($play == 'HE'){
                    $re_play = 'HZ';
                }
                
                if ($re_play == 'HZ'){
                    $spk  = '';
                    if ($v == '大'){
                        $spk = 'DA';
                    }elseif ($v == '小'){
                        $spk = 'XIAO';
                    }elseif ($v == '单'){
                        $spk = 'DAN';
                    }elseif ($v == '双'){
                        $spk = 'SHUANG';
                    }else{
                        $spk = $v;
                    }
                }
                $orderItem[$k]['odds'] = $codeKeyList['TSK3-']['K3|'][$re_play . $spk]['odds'];
            }
            break;
        case 'SBTH':
            // 三不同号，三个号码起算一注，计算投注内容中三不同号计算出的所有投注内容
            // odds赔率为一致
            $orderItem = array();
            for($i = 0; $i < count($bettingData) - 2; $i++){
                for($j = $i + 1; $j < count($bettingData); $j++){
                    for($k = $j + 1; $k < count($bettingData); $k++){
//                         $item['order_no']   = $orderno;
                        $item['betting_str']= $data['bet'];
                        $item['lott_id']    = $data['lott_id'];
                        
                        $item['en_play']    = $play;
                        $item['cn_play']    = $p_conf['title'];
                        $item['betting_no'] = $bettingData[$i] . ',' . $bettingData[$j] . ',' . $bettingData[$k];
                        $item['num']        = 1;    // 手机端每次投注都是1注
                        $item['multiple']   = 1;    // K3默认倍数
                        $item['money_unit'] = 1;    // K3默认金额单位
                        $item['eo_money']   = $data['eo_money'];
                        // 总金额 = 投注数num*倍数multiple*金额单位money_unit*单注基础金额数eo_money
                        $item['money']      = $item['num'] * $item['multiple'] * $item['money_unit'] * $item['eo_money'];
//                         $item['odds']       = $oddsTitleKey[$bettingData[$i]]['odds'];
                        $item['prize']      = '0';
                        $item['winner']     = '0';
                        
                        $item['odds'] = $codeKeyList['TSK3-']['K3|'][$play . $spk]['odds'];
                        $orderItem[]        = $item;
                        $order_pay += 1 * $data['eo_money'];
                    }
                }
            }
            break;
        case 'ETHDX':
            // 投注选号做处理， 一对相同号与单独号分开整理。
            $singleNo = array();
            $doubleNo = array();
            foreach ($bettingData as $k => $v){
                if (strlen($v) > 1){
                    $doubleNo[] = $v;
                }else{
                    $singleNo[] = $v;
                }
            }
            $orderItem = array();
            foreach ($doubleNo as $k => $v){
                foreach ($singleNo as $sk => $sv){
                    $item['betting_str']= $data['bet'];
                    $item['lott_id']    = $data['lott_id'];
                    
                    $item['en_play']    = $play;
                    $item['cn_play']    = $p_conf['title'];
                    $item['betting_no'] = $v . ',' . $sv;
                    $item['num']        = 1;    // 手机端每次投注都是1注
                    $item['multiple']   = 1;    // K3默认倍数
                    $item['money_unit'] = 1;    // K3默认金额单位
                    $item['eo_money']   = $data['eo_money'];
                    // 总金额 = 投注数num*倍数multiple*金额单位money_unit*单注基础金额数eo_money
                    $item['money']      = $item['num'] * $item['multiple'] * $item['money_unit'] * $item['eo_money'];
//                     $item['odds']       = $oddsTitleKey[$v]['odds'];
                    $item['prize']      = '0';
                    $item['winner']     = '0';
                    $item['odds'] = $codeKeyList['TSK3-']['K3|'][$play . $spk]['odds'];
                    $orderItem[]        = $item;
                    $order_pay += 1 * $data['eo_money'];
                }
            }
            break;
        case 'EBTH':
            // 二不同号，两个号码起算一注，计算投注内容中二不同号计算出的所有投注内容
            // odds赔率为一致
            $orderItem = array();
            for($i = 0; $i < count($bettingData) - 1; $i++){
                for($j = $i + 1; $j < count($bettingData); $j++){
                    $item['betting_str']= $data['bet'];
                    $item['lott_id']    = $data['lott_id'];
                    
                    $item['en_play']    = $play;
                    $item['cn_play']    = $p_conf['title'];
                    $item['betting_no'] = $bettingData[$i] . ',' . $bettingData[$j];
                    $item['num']        = 1;    // 手机端每次投注都是1注
                    $item['multiple']   = 1;    // K3默认倍数
                    $item['money_unit'] = 1;    // K3默认金额单位
                    $item['eo_money']   = $data['eo_money']; // 每注基础金额数
                    // 总金额 = 投注数num*倍数multiple*金额单位money_unit*单注基础金额数eo_money
                    $item['money']      = $item['num'] * $item['multiple'] * $item['money_unit'] * $item['eo_money'];
//                     $item['odds']       = $oddsTitleKey[$bettingData[$i]]['odds'];
                    $item['prize']      = '0';
                    $item['winner']     = '0';
                    $item['odds'] = $codeKeyList['TSK3-']['K3|'][$play . $spk]['odds'];
                    $orderItem[]        = $item;
                    $order_pay += 1 * $data['eo_money'];
                }
            }
            break;
        default:
            break;
    }
    // 统一设置订单主表信息
    $orderMain['lott_id']        = $data['lott_id'];
    $orderMain['uid']            = $data['uid'];
    $orderMain['order_no']       = $orderno;
    $orderMain['code']           = $data['bet'];
    $orderMain['period']         = '';
    $orderMain['status']         = '0';
    $orderMain['platform']       = $data['platform'];
    $orderMain['prize']          = '0';
    $orderMain['createtime']     = time();
    $orderMain['amount']         = $order_pay;
    return array( 'lott_play' => $data['lottInfo']['title'], 'orderData' => array('main' => $orderMain, 'item' => $orderItem));
} 

/**
 * 十一选五
 * @param object $data
 */
function betting_syxw($data){
    global $db;
    // 十一选五玩法配置载入
    $p_conf    = syxwItem();
    // 订单主表:原设计不分订单主从表， 这里重新加入统一订单主从。
    $orderMain = array();
    // 订单副表
    $orderItem = array();
    $weimiao   = microtime(true);
    $orderno   = 'TZ' . date('YmdHis') . str_pad(substr($weimiao, strpos($weimiao, '.') + 1), '4', 0);
    $order_pay = 0;
    $order_amount = 0;
    $lott_id   = 0;
    $bet_arr   = array();
    $nowTime          = time();
    $lott_id          = $data['post'][0]->lott_id;
    $perTab           = Table('lottery_k3');
    // 防止用户选号后等下一期的时候提交，期号会保持上一期的数据，这里获取最新的期号信息来填充数据
    $nowPeriodInfoSql = 'SELECT id FROM ' . $perTab . ' WHERE tid = ' . $lott_id . ' AND starttime <= ' . $nowTime . ' ORDER BY id DESC LIMIT 1';
    $nowPeriodInfo    = $db->getrow($nowPeriodInfoSql);
    
    // 返点赔率信息
    $codeKeyList    = getUserRpsData($db, $lott_id);
    // 标识是否追号订单
    $is_chase  = 0;
    if($data['post'][0]->chase == 1){
        $is_chase = 1;
        // 整理所有追号期数，以IdKey形式返回（所有追号期数是基础，另外有信息对应所选择的期数）
        $allQishuIdKey = array();
        foreach ($data['post'][0]->ready_bet as $key => $value){
            $allQishuIdKey[$value->chase_period] = $value;
        }
        $playName = explode('-', $data['post'][0]->ready_bet[0]->chase_betName);
        foreach ($data['post'][0]->ready_bet as $ak => $av){
            // 检查当前期号是否已经开奖，开奖则属于有恶意提交数据，（用户攒着投注等开奖后提交）
            $checkFlag = 'SELECT id FROM ' . $perTab . ' WHERE id = ' . $av->chase_period . ' AND `code` != ""';
            $check     = $db->getrow($checkFlag);
            // 如果当前期号已经有开奖数据，则跳过
            if ($check['id']) continue;
            
            // 设置基本信息
            $tmp = array();
            if(!$lott_id){
                $lott_id = $av->chase_lottid;
            }
            if(!in_array($av->chase_betting, $bet_arr)) array_push($bet_arr, $av->chase_betting);
            $item['period_id']  = $av->chase_period;
            $item['lott_id']    = $av->chase_lottid;
            $item['en_play']    = $av->chase_betName;
            $item['cn_play']    = $p_conf['mainItem'][$playName[0]]['play_name'] . ' - ' . $p_conf['mainItem'][$playName[0]]['play'][$playName[1]]['name'];
            $item['betting_str']= $av->chase_betting;
            $item['prize']      = '0';
            $item['winner']     = '0';
            $item['chase']      = '1';
            foreach ($av->chase_bet as $bk1 => $bv1){
                $item['betting_no'] = implode(',', $bv1->bet);
                $item['num']        = 1;                             // 注数
                $item['multiple']   = $av->chase_beishu;             // 倍数
                $item['eo_money']   = $bv1->eo_money;                // 每注基础金额数
                $item['money_unit'] = $av->chase_betUnit;            // 投注金额单位
                $item['money']      = $item['num'] * $item['multiple'] * $item['money_unit'] * $item['eo_money'];  // 当前注的金额=投注数*投注倍数*金额单位*每注金额
                if ($data['post'][0]->winnerEnd){
                    $item['winner_end'] = $data['post'][0]->winnerEnd;
                }
                // 针对十一选五，查找当前用户对应的赔率盈利数据
                $playCodeData = explode('-', $value->bet_name);
                $spk          = '';
                if ($playCodeData[0] == 'QWX'){
                    // 趣味型是多赔率玩法，这里对投注项一一识别，设置赔率
                    if ($playCodeData[1] == 'CZW'){
                        $spk = '0' . $item['betting_no'];
                    }elseif ($playCodeData[1] == 'DDS'){
                        $spk = findNum($item['betting_no']);
                    }
                }
                $item['odds'] = $codeKeyList[$playCodeData[0] . '-'][$playCodeData[0] . '|'][$playCodeData[1] . $spk]['odds'];
                
                $orderItem[]   = $item;
                $order_pay    += 1 * $data['eo_money'];
                $order_amount += $item['money'];
            }
        }
    }else{
        foreach ($data['post'] as $key => $value) {
            $playName = explode('-', $value->bet_name);
            $bets     = syxw_read_betting(array('betting' => $value->betting, 'bet_item' => $value->bet_item), $value->bet_name);
            $tmpItem  = (array)$value->bet_item;
            $baseMultiple = 0;
            foreach ($tmpItem as $tk1 => $tv1){
                $baseMultiple = $tv1->multiple;
                break;
            }
            if(!in_array($value->bet_string, $bet_arr)) array_push($bet_arr, $value->bet_string);
            foreach ($bets as $bk => $bv){
                if(!$lott_id){
                    $lott_id = $value->lott_id;
                }
                // 设置基本信息
                $tmp = array();
                $item['period_id']  = $nowPeriodInfo['id'];
                $item['lott_id']    = $value->lott_id;
                $item['en_play']    = $value->bet_name;
                $item['cn_play']    = $p_conf['mainItem'][$playName[0]]['play_name'] . ' - ' . $p_conf['mainItem'][$playName[0]]['play'][$playName[1]]['name'];
                $item['betting_str']= $value->bet_string;
                $item['betting_no'] = implode(',', $bv);
                $item['num']        = 1;                             // 注数（只有倍数，默认1注
                $item['multiple']   = $value->bet_beishu;            // 倍数
                $item['eo_money']   = $value->eo_money;              // 每注基础金额数
                $item['money_unit'] = $value->bet_money_unit;        // 投注金额单位
                $item['money']      = $item['num'] * $item['multiple'] * $item['money_unit'] * $item['eo_money'];  // 当前注的金额=投注数*投注倍数*金额单位*每注金额
                $item['prize']      = '0';
                $item['winner']     = '0';
                // 针对十一选五，查找当前用户对应的赔率盈利数据
                $playCodeData = explode('-', $value->bet_name);
                $spk          = '';
                if ($playCodeData[0] == 'QWX'){
                    // 趣味型是多赔率玩法，这里对投注项一一识别，设置赔率
                    if ($playCodeData[1] == 'CZW'){
                        $spk = '0' . $item['betting_no'];
                    }elseif ($playCodeData[1] == 'DDS'){
                        $spk = findNum($item['betting_no']);
                    }
                }
                $item['odds'] = $codeKeyList[$playCodeData[0] . '-'][$playCodeData[0] . '|'][$playCodeData[1] . $spk]['odds'];
                
                $orderItem[]        = $item;
                $order_pay += 1 * $data['eo_money'];
                $order_amount += $item['money'];
            }
        }
    }
    // 统一设置订单主表信息
    $orderMain['lott_id']        = $lott_id;    // 当前订单是针对哪个彩种的
    $orderMain['uid']            = $data['uid'];
    $orderMain['order_no']       = $orderno;
    $orderMain['code']           = '';          // 投注内容组合字符串
    $orderMain['period']         = '';          // 混合投注多个期号，期号记录到item中
    $orderMain['status']         = '0';
    $orderMain['platform']       = $data['platform'];
    $orderMain['prize']          = '0';
    $orderMain['createtime']     = time();
    $orderMain['amount']         = $order_amount;
    $orderMain['code']           = implode('#', $bet_arr);
    $orderMain['is_chase']       = $is_chase;
    return array('main' => $orderMain, 'item' => $orderItem, 'lott_title' => '十一选五');
}

/**
 * 手机版的十一选五，单独做一个请求内容格式更合理的方法
 */
function betting_syxw_wap_chase($param){
    global $db;
    $perTble        = Table('lottery_k3');
    $lott_id        = $param['post'][0]->lott_id;
    // 标识是否追号订单
    $is_chase       = 0;
    // 获取到当前投注的彩种信息
    $checkLottSql   = 'SELECT id FROM ' . Table('lottery') . ' WHERE id = "' . $lott_id . '"';
    $checkLottInfo  = $db->getrow($checkLottSql);
    if (!$checkLottInfo) return;
    // 获取web版追号期数信息
    $limit          = ' LIMIT ' . $param['qishu'];
    $nowPerSql      = 'SELECT id, `code` FROM ' . $perTble . ' WHERE tid = ' . $lott_id . ' AND starttime <= ' . time() . ' ORDER BY id DESC LIMIT 1';
    $nowPerInfo     = $db->getrow($nowPerSql);
    $chasePerList   = array();
    if ($param['qishu'] > 1){
        $is_chase     = 1;
        $chasePerSql  = 'SELECT id, `code` FROM ' . $perTble . ' WHERE tid = ' . $lott_id . ' AND starttime > ' . time() . ' ORDER BY id ASC LIMIT ' . ($param['qishu'] - 1);
        $chasePerList = $db->getall($chasePerSql);
    }
    array_unshift($chasePerList, $nowPerInfo);
    // 记录投注内容
    $bet_arr        = array();
    // 十一选五玩法配置载入
    $p_conf         = syxwItem();
    
    // 返点赔率信息
    $codeKeyList    = getUserRpsData($db, $lott_id);
    
    // 订单信息准备
    $weimiao        = microtime(true);
    $orderno        = 'TZ' . date('YmdHis') . str_pad(substr($weimiao, strpos($weimiao, '.') + 1), '4', 0);
    foreach ($chasePerList as $k => $v){
        // 已经有了开奖， 则跳过
        if ($v['code']) continue;
        // 对每一期投注进行投注内容计算
        foreach ($param['post'] as $key => $value){
            $playName = explode('-', $value->bet_name);
            // 每一个投注内容包含的投注号
            foreach ($value->bet_item as $k1 => $v1){
                if(!in_array($value->bet_string, $bet_arr)) array_push($bet_arr, $value->bet_string);
                // 设置基本信息
                $tmp = array();
                $item['period_id']  = $v['id'];
                $item['lott_id']    = $lott_id;
                $item['en_play']    = $value->bet_name;
                $item['cn_play']    = $p_conf['mainItem'][$playName[0]]['play_name'] . ' - ' . $p_conf['mainItem'][$playName[0]]['play'][$playName[1]]['name'];
                $item['betting_str']= $value->bet_string;
                $item['betting_no'] = implode(',', $v1->bet);
                $item['num']        = 1;                    // 注数（手机版默认单注，只有倍数
                $item['multiple']   = $v1->multiple;        // 倍数
                $item['eo_money']   = $v1->eo_money;        // 每注基础金额数
                $item['money_unit'] = $value->bet_money_unit; // 投注金额单位
                $item['money']      = $item['num'] * $item['multiple'] * $item['money_unit'] * $item['eo_money'];  // 当前注的金额=投注数*投注倍数*金额单位*每注金额
                $item['prize']      = '0';
                $item['winner']     = '0';
                $item['chase']      = '1';
                if ($data['post'][0]->winnerEnd){
                    $item['winner_end'] = $data['post'][0]->winnerEnd;
                }
                
                // 针对十一选五，查找当前用户对应的赔率盈利数据
                $playCodeData = explode('-', $value->bet_name);
                $spk          = '';
                if ($playCodeData[0] == 'QWX'){
                    // 趣味型是多赔率玩法，这里对投注项一一识别，设置赔率
                    if ($playCodeData[1] == 'CZW'){
                        $spk = '0' . $item['betting_no'];
                    }elseif ($playCodeData[1] == 'DDS'){
                        $spk = findNum($item['betting_no']);
                    }
                }
                $item['odds'] = $codeKeyList[$playCodeData[0] . '-'][$playCodeData[0] . '|'][$playCodeData[1] . $spk]['odds'];
                
                $orderItem[]   = $item;
                $order_amount += $item['money'];
            }
        }
    }
    // 统一设置订单主表信息
    $orderMain['lott_id']        = $lott_id;    // 当前订单是针对哪个彩种的
    $orderMain['uid']            = $param['uid'];
    $orderMain['order_no']       = $orderno;
    $orderMain['code']           = '';          // 投注内容组合字符串
    $orderMain['period']         = '';          // 混合投注多个期号，期号记录到item中
    $orderMain['status']         = '0';
    $orderMain['platform']       = $param['platform'];
    $orderMain['prize']          = '0';
    $orderMain['createtime']     = time();
    $orderMain['amount']         = $order_amount;
    $orderMain['code']           = implode('#', $bet_arr);
    $orderMain['is_chase']       = $is_chase;
    return array('main' => $orderMain, 'item' => $orderItem, 'lott_title' => '十一选五');
}

/**
 * 手机版的时时彩
 */
function betting_ssc($param){
    global $db;
    $perTble        = Table('lottery_k3');
    $lott_id        = $param['post'][0]->lott_id;
    // 标识是否追号订单
    $is_chase       = 0;
    // 获取到当前投注的彩种信息
    $checkLottSql   = 'SELECT id FROM ' . Table('lottery') . ' WHERE id = "' . $lott_id . '"';
    $checkLottInfo  = $db->getrow($checkLottSql);
    if (!$checkLottInfo) return;
    // 追号的倍数设置
    $chasePerData   = array();
    if (count($param['chasePeriodData']) > 1){
        $is_chase = 1;
    }
    foreach ($param['chasePeriodData'] as $pk => $pv){
        $per_str = explode('_', $pv);
        $checkPerSql  = 'SELECT id, `code` FROM ' . $perTble . ' WHERE id = ' . $per_str[0];
        $checkPerInfo = $db->getrow($checkPerSql);
        if (!$checkPerInfo || $checkPerInfo['code']){
            // 如果当前校验的期号信息不存在或者已经有了开奖信息， 则不统计
            continue;
        }
        $chasePerData[] = array(
            'period_id' => $per_str[0],
            'multiple'  => $per_str[1],
        );
    }
    
    // 返点赔率信息
    $codeKeyList    = getUserRpsData($db, $lott_id);
    
    // 记录投注内容
    $bet_arr        = array();
    // 时时彩玩法配置载入
    $p_conf         = sscItem();
    // 订单信息准备
    $weimiao        = microtime(true);
    $orderno        = 'TZ' . date('YmdHis') . str_pad(substr($weimiao, strpos($weimiao, '.') + 1), '4', 0);
    foreach ($chasePerData as $ck => $cv){
        // 对每一期投注进行投注内容计算
        foreach ($param['post'] as $key => $value){
            $playName = explode('-', $value->bet_name);
            $playType = explode('|', $playName[1]);
            // 每一个投注内容包含的投注号
            foreach ($value->bet_item as $k1 => $v1){
                if(!in_array($value->bet_string, $bet_arr)) array_push($bet_arr, $value->bet_string);
                // 设置基本信息
                $tmp = array();
                $item['period_id']  = $cv['period_id'];
                $item['lott_id']    = $lott_id;
                $item['en_play']    = $value->bet_name;
                $item['cn_play']    = $p_conf['mainPlay'][$playName[0]]['title'] . ' - ' .
                $p_conf['mainPlay'][$playName[0]]['playType'][$playType[0]]['title'] . ' - ' .
                $p_conf['mainPlay'][$playName[0]]['playType'][$playType[0]]['followPlay'][$playType[1]]['title'];
                $item['betting_str']= $value->bet_string;
                $item['betting_no'] = implode(',', $v1->bet);
                $item['num']        = 1;                      // 注数 （只有倍数，注数默认单注）
                $item['multiple']   = $cv['multiple'] ? $cv['multiple'] : $v1->multiple;     // 倍数
                $item['eo_money']   = $v1->eo_money;          // 每注基础金额数
                $item['money_unit'] = $value->bet_money_unit; // 投注金额单位
                $item['money']      = $item['num'] * $item['multiple'] * $item['money_unit'] * $item['eo_money'];  // 当前注的金额=投注数*投注倍数*金额单位*每注金额
    
                $item['prize']      = '0';
                $item['winner']     = '0';
                $item['chase']      = $param['qishu'] ? '1' : '0';
                if ($data['post'][0]->winnerEnd){
                    $item['winner_end'] = $data['post'][0]->winnerEnd;
                }
                
                // 针对十一选五，查找当前用户对应的赔率盈利数据
                $tmpCodeKey   = explode('-', $value->bet_name);
                $playCodeData = explode('|', $tmpCodeKey[1]);
                array_unshift($playCodeData, $tmpCodeKey[0]);
                $spk          = '';
                if ($playCodeData[0] == 'WU_X'){
                    // 趣味型是多赔率玩法，这里对投注项一一识别，设置赔率
                    if ($playCodeData[1] == 'QW'){
                        $playCodeData[1] .= 'X';
                    }
                }
                $item['odds'] = $codeKeyList[$playCodeData[0] . '-'][$playCodeData[1] . '|'][$playCodeData[2] . $spk]['odds'];
                
                $orderItem[]   = $item;
                $order_amount += $item['money'];
            }
        }
    }
    // 统一设置订单主表信息
    $orderMain['lott_id']        = $lott_id;    // 当前订单是针对哪个彩种的
    $orderMain['uid']            = $param['uid'];
    $orderMain['order_no']       = $orderno;
    $orderMain['code']           = '';          // 投注内容组合字符串
    $orderMain['period']         = '';          // 混合投注多个期号，期号记录到item中
    $orderMain['status']         = '0';
    $orderMain['platform']       = $param['platform'];
    $orderMain['prize']          = '0';
    $orderMain['createtime']     = time();
    $orderMain['amount']         = $order_amount;
    $orderMain['code']           = implode('#', $bet_arr);
    $orderMain['is_chase']       = $is_chase;
    return array('main' => $orderMain, 'item' => $orderItem, 'lott_title' => '时时彩');
}

/**
 * 手机版的时时彩
 */
function betting_ssc_wap_chase($param){
    global $db;
    $perTble        = Table('lottery_k3');
    $lott_id        = $param['post'][0]->lott_id;
    // 标识是否追号订单
    $is_chase       = 0;
    // 获取到当前投注的彩种信息
    $checkLottSql   = 'SELECT id FROM ' . Table('lottery') . ' WHERE id = "' . $lott_id . '"';
    $checkLottInfo  = $db->getrow($checkLottSql);
    if (!$checkLottInfo) return;
    // 获取web版追号期数信息
    $limit          = ' LIMIT ' . $param['qishu'];
    $nowPerSql      = 'SELECT id, `code` FROM ' . $perTble . ' WHERE tid = ' . $lott_id . ' AND starttime <= ' . time() . ' ORDER BY id DESC LIMIT 1';
    $nowPerInfo     = $db->getrow($nowPerSql);
    $chasePerList   = array();
    if ($param['qishu'] > 1){
        $is_chase   = 1;
        $chasePerSql  = 'SELECT id, `code` FROM ' . $perTble . ' WHERE tid = ' . $lott_id . ' AND starttime > ' . time() . ' ORDER BY id ASC LIMIT ' . ($param['qishu'] - 1);
        $chasePerList = $db->getall($chasePerSql);
    }
    array_unshift($chasePerList, $nowPerInfo);
    // 记录投注内容
    $bet_arr        = array();
    // 时时彩玩法配置载入
    $p_conf         = sscItem();
    // 返点赔率信息
    $codeKeyList    = getUserRpsData($db, $lott_id);
    
    // 订单信息准备
    $weimiao        = microtime(true);
    $orderno        = 'TZ' . date('YmdHis') . str_pad(substr($weimiao, strpos($weimiao, '.') + 1), '4', 0);
    foreach ($chasePerList as $k => $v){
        // 已经有了开奖， 则跳过
        if ($v['code']) continue;
        // 对每一期投注进行投注内容计算
        foreach ($param['post'] as $key => $value){
            $playName = explode('-', $value->bet_name);
            $playType = explode('|', $playName[1]);
            // 每一个投注内容包含的投注号
            foreach ($value->bet_item as $k1 => $v1){
                if(!in_array($value->bet_string, $bet_arr)) array_push($bet_arr, $value->bet_string);
                // 设置基本信息
                $tmp = array();
                $item['period_id']  = $v['id'];
                $item['lott_id']    = $lott_id;
                $item['en_play']    = $value->bet_name;
                $item['cn_play']    = $p_conf['mainPlay'][$playName[0]]['title'] . ' - ' . 
                                        $p_conf['mainPlay'][$playName[0]]['playType'][$playType[0]]['title'] . ' - ' . 
                                        $p_conf['mainPlay'][$playName[0]]['playType'][$playType[0]]['followPlay'][$playType[1]]['title'];
                $item['betting_str']= $value->bet_string;
                $item['betting_no'] = implode(',', $v1->bet);
                $item['num']        = 1;                      // 注数 （只有倍数，注数默认单注）
                $item['multiple']   = $param['multiple'] ? $param['multiple'] : $value->multiple;     // 倍数
                $item['eo_money']   = $v1->eo_money;          // 每注基础金额数
                $item['money_unit'] = $value->bet_money_unit; // 投注金额单位
                $item['money']      = $item['num'] * $item['multiple'] * $item['money_unit'] * $item['eo_money'];  // 当前注的金额=投注数*投注倍数*金额单位*每注金额
                
                $item['odds']       = $p_conf['mainPlay'][$playName[0]]['playType'][$playType[0]]['followPlay'][$playType[1]]['winnerMoney'];
                
                $item['prize']      = '0';
                $item['winner']     = '0';
                $item['chase']      = $param['qishu'] ? '1' : '0';
                if ($data['post'][0]->winnerEnd){
                    $item['winner_end'] = $data['post'][0]->winnerEnd;
                }
                
                // 针对十一选五，查找当前用户对应的赔率盈利数据
                $tmpCodeKey   = explode('-', $value->bet_name);
                $playCodeData = explode('|', $tmpCodeKey[1]);
                array_unshift($playCodeData, $tmpCodeKey[0]);
                $spk          = '';
                if ($playCodeData[0] == 'WU_X'){
                    // 趣味型是多赔率玩法，这里对投注项一一识别，设置赔率
                    if ($playCodeData[1] == 'QW'){
                        $playCodeData[1] .= 'X';
                    }
                }
                $item['odds'] = $codeKeyList[$playCodeData[0] . '-'][$playCodeData[1] . '|'][$playCodeData[2] . $spk]['odds'];
                
                $orderItem[]   = $item;
                $order_amount += $item['money'];
            }
        }
    }
    // 统一设置订单主表信息
    $orderMain['lott_id']        = $lott_id;    // 当前订单是针对哪个彩种的
    $orderMain['uid']            = $param['uid'];
    $orderMain['order_no']       = $orderno;
    $orderMain['code']           = '';          // 投注内容组合字符串
    $orderMain['period']         = '';          // 混合投注多个期号，期号记录到item中
    $orderMain['status']         = '0';
    $orderMain['platform']       = $param['platform'];
    $orderMain['prize']          = '0';
    $orderMain['createtime']     = time();
    $orderMain['amount']         = $order_amount;
    $orderMain['code']           = implode('#', $bet_arr);
    $orderMain['is_chase']       = $is_chase;
    return array('main' => $orderMain, 'item' => $orderItem, 'lott_title' => '时时彩');
}


/**
 * 解读十一选五的每个投注项所产生的的注号
 */
function syxw_read_betting($betData, $play){
    $data      = $betData['betting'];
    $bet_item  = $betData['bet_item'];
    if (!$data) return;
    $betArr    = array();
    
    if ($bet_item){
        // 导入注单的投注项
        $tmp = array();
        foreach ($bet_item as $key => $value){
            if($value->check == 'error') continue;
            array_push($betArr, $value->bet);
        }
    }
    return $betArr;
}

/**
 * 获取投注人的返点赔率信息
 * @param int $lott_id
 */
function getUserRpsData($db, $lott_id){
    // 载入用户的返点设置信息
    $sql       = '
                SELECT info.`invita_code_id`, inv.`type`, item.`lott_cate_id`, item.`re_point`
                FROM ' . Table('user_info') . ' AS info
                LEFT JOIN ' . Table('user_invita_code') . ' AS inv
                ON info.`invita_code_id` = inv.`id`
                LEFT JOIN ' . Table('user_invita_item') . ' AS item
                ON inv.`id` = item.`code_id`
                WHERE info.`uid` =' . $_SESSION['uid'];
    $rpsInfo   = $db->getall($sql, 'lott_cate_id');
    
    // 获取彩种的基本信息
    $lottInfo  = $db->getrow('SELECT cate_id FROM ' . Table('lottery') . ' WHERE id = ' . $lott_id);
    
    $rpsTab      = Table('repoint_and_odds');
    $planMainTab = Table('lottery_play_main');
    $planFollTab = Table('lottery_play_follow');
    $where       = '';
    foreach ($rpsInfo as $k => $v){
        if ($k == $lottInfo['cate_id']){
            $where = ' WHERE rps.lott_cate_id = "' . $k . '" AND rps.re_point = "' . $v['re_point'] . '"';
            break;
        }
    }
    $sql         = 'SELECT cate.`sname`, main.`en_code` as main_encode, main.`id` as main_id, main.`title` AS main_title, tp.`title` as type_title, tp.`en_code` as type_code,
                fo.`en_code` as foll_encode, fo.`title` AS foll_title, fo.`explain`, fo.`example`,
                rps.`re_point`, rps.`odds`
                FROM ' . $rpsTab . ' AS rps
                LEFT JOIN ' . $planFollTab . ' AS fo
                ON rps.`follow_id` = fo.`id`
                LEFT JOIN ' . $planMainTab . ' AS main
                ON main.`id` = fo.`main_id`
                LEFT JOIN yulin_lottery_category AS cate
                ON main.`cate_id` = cate.`id`
                LEFT JOIN yulin_lottery_play_type AS tp
                ON fo.`type_id` = tp.`id`
                ' . $where;
    $playList    = $db->getall($sql);
    $codeKeyList = array();
    foreach ($playList as $k => $v){
        $v['explain'] = html_entity_decode($v['explain']);
        $codeKeyList[$v['main_encode']][$v['type_code']][$v['foll_encode']] = $v;
    }
    return $codeKeyList;
}

function findNum($str=''){
    $str  = trim($str);
    if(empty($str)) return '';
    // 匹配数字的正则表达式
    for ($i = 0; $i < strlen($str); $i++){
        if(is_numeric($str[$i])){
            $result.=$str[$i];
        }
    }
    return $result;
}

/**
 * 用户投注后的相应返点操作
 * @param $order_amount: 用户下单金额
 * @param $uid         : 下单人
 * @param $lott_id     : 彩种信息
 */
function fanDian($orderData, $orderId){
    global $db;
    // 查询彩种的类别（主要是K3，SSC, SYXW 这种类别）
    $lottInfo   = $db->getrow('SELECT cate_id FROM ' . Table('lottery') . ' WHERE id = ' . $orderData['lott_id']);
    // 查询出当前投注用户的代理阶级信息， 所有代理信息查询出来后，准备计算各代理的返点
    $structData = array();
    getCompleteStructure($db, $structData, $playRps, $orderData['uid'], $lottInfo['cate_id']);
    // 总代
//     $zongdai    = array_pop($structData);
    $zdFd       = 0;
    $structData = array_values($structData);
    $agentData  = array_column($structData, 'uid');
    // 订单总额 * 返点数值 * 百分比基数
    $fdAmountBase = $orderData['amount'] * $playRps['re_point'] * 0.01;
    // 庄家得到50%
    $zdFd       = $fdAmountBase * 0.5;
    // 创建的时间
    $dateline   = time();
    // 庄家的返点保存记录
    $logData = array(
        'uid'          => -1,
        'order_id'     => $orderId,
        'play_uid'     => $orderData['uid'],
        'order_amount' => $orderData['amount'],
        'rps_amount'   => $zdFd,
        'dateline'     => $dateline,
    );
    $db->add('repoint_log', $logData);
    if (count($agentData) == 1){
        // 如果只有一个代理，则剩余的50%归这个代理所有。
        $everyAgentFd = $zdFd;
    }else{
        // 计算每个代理得到多少返点（因为庄家的返点与其他代理返点总额一样，这里用庄家返点金额计算，但是不改变）
        $everyAgentFd = round($zdFd / count($agentData), 3);
    }
    
    // 订单信息准备
    $weimiao        = microtime(true);
    // 给每个代理返点操作
    $ordernoPrefix      = 'RP' . date('YmdHis');
    $ordernoSuffix      = str_pad(substr($weimiao, strpos($weimiao, '.') + 1), '4', 0);
    foreach ($agentData as $k => $v){
        $tmp = [];
        $tmp['uid']     = $v;
        $tmp['tid']     = 'repoint';
        $tmp['lkey']    = $ordernoPrefix . ($ordernoSuffix + $k);
        $tmp['money']   = $everyAgentFd;
        $tmp['balance'] = +$everyAgentFd;
        $tmp['notes']   = '玩家购买彩票，获得返点。玩家投注金额【' . $orderData['amount'] . '】，获得返点数额【' . $everyAgentFd . '】';
        MoneyLog($tmp);
        
        // 记录特殊对应的返点记录表
        $logData = array(
            'uid'          => $v,
            'order_id'     => $orderId,
            'play_uid'     => $orderData['uid'],
            'order_amount' => $orderData['amount'],
            'rps_amount'   => $everyAgentFd,
            'dateline'     => $dateline,
        );
        $db->add('repoint_log', $logData);
    }
}

/**
 * 根据传入的用户id， 查找上面所有的代理信息
 * @param unknown $db
 * @param unknown $data         : 返回的代理返点信息
 * @param unknown $playRps      ： 如果是玩家，玩家的返点信息
 * @param unknown $uid          ： 
 * @param unknown $lott_cate_id
 */
function getCompleteStructure($db, &$data, &$playRps, $uid, $lott_cate_id){
    // 获取用户的基本信息
    $sql      = 'SELECT invita_code_id, user_type FROM ' . Table('user_info') . ' WHERE uid = ' . $uid;
    $userInfo = $db->getrow($sql);
    // 查询邀请码信息
    $sql      = 'SELECT id, uid FROM ' . Table('user_invita_code') . ' WHERE id = ' . $userInfo['invita_code_id'];
    $codeInfo = $db->getrow($sql);
    // 查询邀请码的详细设置信息
    $sql      = 'SELECT lott_cate_id, re_point FROM ' . Table('user_invita_item') . ' WHERE code_id = ' . $codeInfo['id'] . ' AND lott_cate_id = ' . $lott_cate_id;
    $itemInfo = $db->getrow($sql);
    // 投注者赔率信息
    if (!$playRps){
        $playRps = array(
            'uid'       => $uid,
            'user_type' => $userInfo['user_type'],
            'code_id'   => $codeInfo['id'],
            'agent_id'  => $codeInfo['uid'],
            'lott_cate_id' => $itemInfo['lott_cate_id'],
            're_point'     => $itemInfo['re_point'],
        );
    }
    if ($userInfo['user_type'] == 1){
        // 如果当前用户类型是代理，则也算自己的返点
        $data[$uid] = array(
            'uid'       => $uid,
            'user_type' => $userInfo['user_type'],
            'code_id'   => $codeInfo['id'],
            'agent_id'  => $codeInfo['uid'],
            'lott_cate_id' => $itemInfo['lott_cate_id'],
            're_point'     => $itemInfo['re_point'],
        );
    }
    if ($codeInfo['uid'] != -1){
        getCompleteStructure($db, $data, $playRps, $codeInfo['uid'], $lott_cate_id);
    }
}
















